package org.devio.`as`.proj.common.flutter

import android.content.Context
import io.flutter.embedding.engine.loader.FlutterLoader
import java.io.File

class HiFlutterLoader : FlutterLoader() {

    companion object {
        const val FIX_SO = "libappfix.so"
        private var instance: HiFlutterLoader? = null
            get() {
                if (field == null) {
                    field = HiFlutterLoader()
                }
                return field
            }

        fun get(): HiFlutterLoader {
            return instance!!
        }
    }

    override fun ensureInitializationComplete(
        applicationContext: Context,
        args: Array<out String>?
    ) {
        val path = applicationContext.filesDir
        val soFile = File(path, FIX_SO)
        if (soFile.exists()){
            //反射FlutterLoader:aotSharedLibraryName将libapp.so替换成新的so路径
            val field = FlutterLoader::class.java.getDeclaredField("aotSharedLibraryName")
            field.isAccessible = true;
            field[this] = soFile.absolutePath
        }
        // 在FlutterJNI.nativeInit之前将so路径替换好
        super.ensureInitializationComplete(applicationContext, args)
    }
}